package com.example.myapplication.RxJava;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.example.myapplication.R;

import java.io.InputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;


public class RxJavaActivity extends AppCompatActivity {

    private final static String PATH = "https://b.zol-img.com.cn/soft/5/493/ceNcIqcSrEEgE.jpg";
    private ProgressDialog progressDialog;
    ImageView image;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rx_java);
        image = findViewById(R.id.rx_image);
    }

    public void showImageAction(View view) {

        ///TODO 第二步，分发PATH路径
        ///调用被观察者类.的just方法
        Observable.just(PATH)
                ///TODO 第三步：开始事件下载，

                ///001,第一个map处理，获取图片
                .map(new Function<String, Bitmap>() {
                    @NonNull
                    @Override
                    public Bitmap apply(String path) throws Exception {
                        try{
                            Log.i("TAG", "bitmap: -------:a1");
                            URL url = new URL(path);
                            Log.i("TAG", "bitmap: -------:a2");
                                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
                                Log.i("TAG", "bitmap: -------:a3");
                                httpsURLConnection.setConnectTimeout(5000);
                                Log.i("TAG", "bitmap: -------:aa");

                                int responseCode = httpsURLConnection.getResponseCode();

                                Log.i("TAG", "bitmap: -------:b");
                                if(responseCode == HttpsURLConnection.HTTP_OK){
                                    InputStream inputStream = httpsURLConnection.getInputStream();
                                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                                    Log.i("TAG", "bitmap: -------:"+bitmap);
                                    return bitmap;
                                }
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        return null;
                    }
                })
                ///002,第二个map处理，添加加水印
                .map(new Function<Bitmap, Bitmap>() {
                    @NonNull
                    @Override
                    public Bitmap apply(Bitmap bitmap) throws Throwable {
                        Paint paint = new Paint();
                        paint.setColor(Color.WHITE);
                        paint.setTextSize(200);
                        return drawTextToBitmap(bitmap,"HYY",paint,1000,1000);
                    }
                })
                ///003,第三个map处理，添加记录日志
                .map(new Function<Bitmap, Bitmap>() {
                    @Override
                    public Bitmap apply(Bitmap bitmap) throws Throwable {
                        Log.i("","什么时候下载了图片 apply"+System.currentTimeMillis());
                        return bitmap;
                    }
                })
                .subscribeOn(Schedulers.io())///给上面分配异步线程
                .observeOn(AndroidSchedulers.mainThread())///给终点分配主线程
                ///关联：观察者模式 关联（ 起点 和 终点） == 订阅
                ///subscribe是完整的订阅流程，而onSubscribe只是订阅的第一步。
                .subscribe(new Observer<Bitmap>() {

                    ///TODO 第一步，订阅成功
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        Log.i("TAG", "onSubscribe: -------0");
                        progressDialog = new ProgressDialog(RxJavaActivity.this);
                        progressDialog.setTitle("RxJava Derry run 正在加载中。。");
                        progressDialog.show();
                    }

                    ///TODO 第四步，接受，上一层给我的响应
                    @Override
                    public void onNext(@NonNull Bitmap bitmap) {

                        Log.i("TAG", "onNext: -------1");
                        image.setImageBitmap(bitmap);

                    }

                    ///响应式链条发生异常
                    @Override
                    public void onError(@NonNull Throwable e) {

                        Log.i("TAG", "onError: -------2");
                    }

                    ///TODO 第五步，完成，响应式链条结束
                    @Override
                    public void onComplete() {
                        Log.i("TAG", "onComplete: -------3");
                        if(progressDialog!=null){
                            progressDialog.dismiss();
                        }
                    }
                });
    }
    private final Bitmap drawTextToBitmap(Bitmap bitmap, String text, Paint paint,int paddingLeft,int paddingTop){
        Bitmap.Config bitmapConfig = bitmap.getConfig();

        paint.setDither(true);
        paint.setFilterBitmap(true);
        if(bitmapConfig == null){
            bitmapConfig = Bitmap.Config.ARGB_8888;
        }
        bitmap  = bitmap.copy(bitmapConfig,true);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawText(text,paddingLeft,paddingTop,paint);
        return  bitmap;
    }

    ///常用操作符
    public void action(View view) {
        String[] string = {"AA","BB","CC"};
        ///调用被观察者类.的fromArray方法
        Observable.fromArray(string)
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        Log.d("","accept=============================="+s);
                    }
                });

    }
}